package nianbao;

import encode_decode.ByteToLongDecoder;
import io.netty.bootstrap.ServerBootstrap;
import io.netty.buffer.Unpooled;
import io.netty.channel.*;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.handler.codec.DelimiterBasedFrameDecoder;
import io.netty.handler.codec.FixedLengthFrameDecoder;
import io.netty.handler.codec.LineBasedFrameDecoder;
import io.netty.handler.codec.string.StringDecoder;

public class NettyServer {

    public static void main(String[] args) {
        EventLoopGroup bossGroup = new NioEventLoopGroup(2);
        EventLoopGroup workerGroup = new NioEventLoopGroup(10);
        try {
            ServerBootstrap serverBootstrap = new ServerBootstrap();
            serverBootstrap.group(bossGroup,workerGroup)
                    .channel(NioServerSocketChannel.class)
                    .option(ChannelOption.SO_BACKLOG,100)
                    .childHandler(new ChannelInitializer<SocketChannel>() {
                        @Override
                        protected void initChannel(SocketChannel socketChannel) throws Exception {
                            //服务器将字节解码为long
                            socketChannel.pipeline()
                                    //固定长度解码器
//                                    .addLast(new FixedLengthFrameDecoder("Hello World".getBytes().length))
                                    //换行符分隔解码器
//                                    .addLast(new LineBasedFrameDecoder(100))
                                    //特殊分隔符解码器
//                                    .addLast(new DelimiterBasedFrameDecoder(100, Unpooled.copiedBuffer("@".getBytes())))
                                    //自定义协议解码器
                                    .addLast(new ByteToMessageProtocalDecoder())
                                    .addLast(new NettyServerHandler());
                        }
                    });
            ChannelFuture channelFuture = serverBootstrap.bind(8888).sync();
            channelFuture.channel().closeFuture().sync();
        } catch (InterruptedException e) {
            e.printStackTrace();
        } finally {
            bossGroup.shutdownGracefully();
            workerGroup.shutdownGracefully();
        }
    }

    /**
     * 服务器处理器
     */
    static class NettyServerHandler extends SimpleChannelInboundHandler<MessageProtocal> {

        //直接读取Long数据
        @Override
        protected void channelRead0(ChannelHandlerContext channelHandlerContext, MessageProtocal s) throws Exception {
            System.out.println("服务器接收到数据-------");
            System.out.println("长度：" + s.getLength());
            System.out.println("内容：" + s.getMessage());
        }
    }
}
